// pages/Course/course.js
const app = getApp();
const sss = require('../son/SHA-1/sha.js');
const totp = require('../son/SHA-1/totp.js');

var judgeCache = true;
var num = 0;
var num_jud = true;
var charts_need_array = [];
var timer;
var lesson_result;
var lesson_result_Array;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    colorArrays: ["#FBCF6D", "#C8C8F7", "#FEBCD9", "#5FE1D1", "#8BD3F9", "#64E1B1", "#12AEF3", "#E29AAD"],
    wlist: [],
    selectData: ['第 1 周', '第 2 周', '第 3 周', '第 4 周', '第 5 周', '第 6 周', '第 7 周', '第 8 周', '第 9 周', '第 10 周', '第 11 周', '第 12 周', '第 13 周', '第 14 周', '第 15 周', '第 16 周', '第 17 周', '第 18 周', '第 19 周', '第 20 周', '第 21 周', ],
    insertion: 5.9,
    radioValues: [{
        'value': '1',
        'selected': true
      },
      {
        'value': '2',
        'selected': false
      },
      {
        'value': '3',
        'selected': false
      },
      {
        'value': '4',
        'selected': false
      },
      {
        'value': '5',
        'selected': false
      },
      {
        'value': '6',
        'selected': false
      },
      {
        'value': '7',
        'selected': false
      },
      {
        'value': '8',
        'selected': false
      },
      {
        'value': '9',
        'selected': false
      },
      {
        'value': '10',
        'selected': false
      },
      {
        'value': '11',
        'selected': false
      },
      {
        'value': '12',
        'selected': false
      },
      {
        'value': '13',
        'selected': false
      },
      {
        'value': '14',
        'selected': false
      },
      {
        'value': '15',
        'selected': false
      },
      {
        'value': '16',
        'selected': false
      },
      {
        'value': '17',
        'selected': false
      },
      {
        'value': '18',
        'selected': false
      },
      {
        'value': '19',
        'selected': false
      },
      {
        'value': '20',
        'selected': false
      },
      {
        'value': '21',
        'selected': false
      },
      {
        'value': '22',
        'selected': false
      },
      {
        'value': '23',
        'selected': false
      },
      {
        'value': '24',
        'selected': false
      },
      {
        'value': '25',
        'selected': false
      },
      {
        'value': '26',
        'selected': false
      },
      {
        'value': '27',
        'selected': false
      },
      {
        'value': '28',
        'selected': false
      },
    ],
    weekNum: 1,
    week_selector_open: 'off',
    offset: 5.95
  },


  /**
   * 
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

  radioChange: function(e) {
    var index = e.currentTarget.dataset.index;
    var arr = this.data.radioValues;
    for (var v in arr) {
      if (v == index) {
        arr[v].selected = true;
      } else {
        arr[v].selected = false;
      }
    }
    this.setData({
      radioValues: arr,
      weekNum: index + 1
    });

    var month = new Date().getMonth() + 1;
    var day = new Date().getDay() - 1;
    if (day == 0) day = 6;
    var date = new Date().getDate();
    var date_Array = new Array();
    let cache = '';
    var step = this.data.weekNow - this.data.weekNum;

    for (let i = 0; i < 7; i++) {
      var temp = new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * (day - i + 7 * step));
      cache = (temp.getMonth() + 1).toString() + '-' + temp.getDate().toString();
      date_Array.push(cache);
    }
    this.setData({
      today_date: date_Array,
    })

    let Index = index;

    function unique(arr) {
      var result = [];
      for (var i = 0; i < arr.length; i++) {
        if (result.indexOf(arr[i]) == -1) {
          result.push(arr[i])
        }
      }
      return result;
    }
    //unique备用函数

    var lesson_result = {};
    var lesson_result_Array = [];
    for (let i = 0; i < app.globalData.Course_Grade.length; i++) {
      for (let j = 0; j < app.globalData.Course_Grade[i].lessons_time.length; j++) {

        lesson_result = {
          "xqj": app.globalData.Course_Grade[i].lessons_time[j].weekday,
          "skjc": app.globalData.Course_Grade[i].lessons_time[j].class_begin,
          "skcd": app.globalData.Course_Grade[i].lessons_time[j].class_over - app.globalData.Course_Grade[i].lessons_time[j].class_begin + 1,
          "kcmc": app.globalData.Course_Grade[i].lessons_time[j].location,
          "kcmd": app.globalData.Course_Grade[i].name + '\n'
        }
        if (Index + 1 <= app.globalData.Course_Grade[i].lessons_time[j].week_to && Index + 1 >= app.globalData.Course_Grade[i].lessons_time[j].week_from && app.globalData.Course_Grade[i].year == app.globalData.term_now_year && app.globalData.Course_Grade[i].semester == app.globalData.term_now_semester) {
          lesson_result_Array.push(lesson_result);
        }
      }
    }
    this.setData({
      wlist: lesson_result_Array,
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;

    var month = new Date().getMonth() + 1;
    var day = new Date().getDay() - 1;
    if (day == 0) {
      day = 6;
    }
    var date = new Date().getDate();
    var date_Array = new Array();
    let cache = '';

    for (let i = 0; i < 7; i++) {
      var temp = new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * (day - i));
      cache = (temp.getMonth() + 1).toString() + '-' + temp.getDate().toString();
      date_Array.push(cache);
    }
    this.setData({
      today_date: date_Array,
    })

    var term_begin_date = app.globalData.term_begin_date;
    if (term_begin_date != null) {
      let date = term_begin_date.split("-");

      var thisDay = new Date();
      var firstDay = new Date(parseInt(date[0]), parseInt(date[1]) - 1, parseInt(date[2])); //本年的第一天,Js月份从0开始记！0就是1月啦。
      //var firstDay = new Date(2019, 2, 2);
      var dayWeek = thisDay.getDay(); //今天周几  
      if (dayWeek == 0) {
        dayWeek = 7;
      }
      var startWeek = firstDay.getDay(); //本年第一天周几  
      if (startWeek == 0) {
        startWeek = 7;
      }
      //第几周  
      var weekNum = Math.ceil(((thisDay.getTime() - firstDay.getTime()) / (24 * 60 * 60 * 1000) - 7 + startWeek) / 7);
      weekNum = weekNum + 1;
      that.setData({
        weekNum: weekNum,
        weekNow: weekNum,
      })
      var radioValues = this.data.radioValues;
      for (let i = 0; i < 28; i++) {
        radioValues[i].selected = false;
      }
      for (let i = 0; i < 28; i++) {
        if (parseInt(radioValues[i].value) == weekNum) {
          radioValues[i].selected = true;
          wx.getSystemInfo({
            success: function(res) {
              that.setData({
                radioValues: radioValues
              })
            },
            fail: function(res) {
              wx.showToast({
                title: '屏宽获取失败',
                duration: 1000
              })
            }
          })

        }
      }

      this.setData({
        index: weekNum,
      });
      app.globalData.cache_for_count = 0;

      function unique(arr) {
        var result = [];
        for (var i = 0; i < arr.length; i++) {
          if (result.indexOf(arr[i]) == -1) {
            result.push(arr[i])
          }
        }
        return result;
      }
      //unique备用函数

      lesson_result = {};
      lesson_result_Array = [];
      for (let i = 0; i < app.globalData.Course_Grade.length; i++) {
        for (let j = 0; j < app.globalData.Course_Grade[i].lessons_time.length; j++) {

          lesson_result = {
            "xqj": app.globalData.Course_Grade[i].lessons_time[j].weekday,
            "skjc": app.globalData.Course_Grade[i].lessons_time[j].class_begin,
            "skcd": app.globalData.Course_Grade[i].lessons_time[j].class_over - app.globalData.Course_Grade[i].lessons_time[j].class_begin + 1,
            "kcmc": app.globalData.Course_Grade[i].lessons_time[j].location,
            "kcmd": app.globalData.Course_Grade[i].name + '\n',
            "course_type": app.globalData.Course_Grade[i].course_type,
            "college": app.globalData.Course_Grade[i].college,
            "instructor": app.globalData.Course_Grade[i].instructor,
            "credit": app.globalData.Course_Grade[i].credit
          }
          if (weekNum <= app.globalData.Course_Grade[i].lessons_time[j].week_to && weekNum >= app.globalData.Course_Grade[i].lessons_time[j].week_from && app.globalData.Course_Grade[i].year == app.globalData.term_now_year && app.globalData.Course_Grade[i].semester == app.globalData.term_now_semester) {
            lesson_result_Array.push(lesson_result);
          }
        }
      }
      this.setData({
        wlist: lesson_result_Array,
      })
    } else if (judgeCache) {
      judgeCache = false;
      this.requestFunction();
      this.Countdown();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  requestFunction: function() {
    var _this = this;
    if (app.globalData.sid != null) {
      _this.setData({
        sid: app.globalData.sid,
      })
    } else {
      _this.setData({
        sid: "尚未登入",
      })
    } //

    //-----数据获取
    if (app.globalData.Course_Grade == null || app.globalData.term_now_year == null) {
      var _this = this;
      wx.getStorage({
        key: 'wifiNumber',
        success: function(res) {
          let cache = res.data;
          app.globalData.pwd_wifi = cache;
          wx.getStorage({
            key: 'stdNumber',
            success: function(res) {
              let cache = res.data;
              if (cache.length == 13) {
                app.globalData.sid = cache;
              }
              wx.getStorage({
                key: 'eduNumber',
                success: function(res) {
                  let cache = res.data;
                  app.globalData.pwd = cache;
                  wx.getStorage({
                    key: 'libNumber',
                    success: function(res) {

                      if (app.globalData.sid != null && app.globalData.sid.length == 13) {
                        _this.setData({
                          sid: app.globalData.sid,
                        })
                      } else {
                        _this.setData({
                          sid: "尚未登入",
                        })
                      } //页面初始化账户信息


                      let cache = res.data;
                      app.globalData.pwd_lib = cache;

                      //数据的获取
                      var sid = app.globalData.sid;
                      var pwd_edu = app.globalData.pwd;
                      var pwd_lib = app.globalData.pwd_lib;
                      var a =
                        wx.request({
                          url: 'https://api.ziqiang.net.cn/token/', //仅为示例，并非真实的接口地址
                          method: "GET",
                          data: {
                            sid: sid,
                            pwd_edu: pwd_edu,
                            pwd_lib: pwd_lib,
                            binding_type: 2
                          },
                          dataType: JSON,
                          header: {
                            'content-type': 'application/json' // 默认值
                          },
                          success: function(res) {
                            _this.setData({
                              isChecked: false,
                            })

                            wx.showToast({
                              title: '登入成功',
                              icon: 'success',
                              duration: 2000,
                            })
                            _this.setData({
                              isAccount: true,
                            })

                            var data = JSON.parse(res.data);

                            app.globalData.Token = data.token;

                            var totpSECRET_KEY = sss.getEncodeString('+.a*vD@JrLYauz(M)HA^=}sh');
                            var secret_key = totp.updateOtp(totpSECRET_KEY);
                            //totp.getCode(totpSECRET_KEY)
                            var timestamp = Math.round(new Date().getTime() / 1000);
                            var timestampstr = timestamp.toString(); //获取unix时间戳字符串
                            var ran = Math.ceil(Math.random() * 1000000000);
                            var ranstr = ran.toString();
                            var arr = new Array(3);
                            arr[0] = secret_key;
                            arr[1] = timestampstr;
                            arr[2] = ranstr;
                            arr = arr.sort(); //字典序排序
                            var mix = arr[0] + arr[1] + arr[2];
                            var sha1 = sss.de2(mix).toString(); //sha1算法
                            var a =
                              wx.request({
                                url: 'https://api.ziqiang.net.cn/courses/', //仅为示例，并非真实的接口地址
                                method: "GET",
                                data: {

                                },
                                dataType: JSON,
                                header: {
                                  'content-type': 'application/json', // 默认值
                                  'Authorization': 'Token ' + app.globalData.Token,
                                  'x-zswd-signature': sha1,
                                  'x-zswd-timestamp': timestamp,
                                  'x-zswd-nonce': ran,
                                },
                                success: function(res) {
                                  let d = new Date();
                                  var day1 = new Date(app.globalData.term_begin_date);
                                  let day_cache = d.getFullYear().toString() + '-' + (d.getMonth() + 1).toString() + '-' + d.getDate().toString();

                                  var day2 = new Date(day_cache);

                                  let Index = Math.ceil((day2 - day1) / (1000 * 60 * 60 * 24) / 7);
                                  Index = Index - 1;
                                  var data = JSON.parse(res.data);
                                  app.globalData.Course_Grade = data;
                                  //////////////////////////////////////


                                  function unique(arr) {
                                    var result = [];
                                    for (var i = 0; i < arr.length; i++) {
                                      if (result.indexOf(arr[i]) == -1) {
                                        result.push(arr[i])
                                      }
                                    }
                                    return result;
                                  }
                                  //unique备用函数

                                  var lesson_result = {};
                                  var lesson_result_Array = [];
                                  for (let i = 0; i < app.globalData.Course_Grade.length; i++) {
                                    for (let j = 0; j < app.globalData.Course_Grade[i].lessons_time.length; j++) {

                                      lesson_result = {
                                        "xqj": app.globalData.Course_Grade[i].lessons_time[j].weekday,
                                        "skjc": app.globalData.Course_Grade[i].lessons_time[j].class_begin,
                                        "skcd": app.globalData.Course_Grade[i].lessons_time[j].class_over - app.globalData.Course_Grade[i].lessons_time[j].class_begin + 1,
                                        "kcmc": app.globalData.Course_Grade[i].lessons_time[j].location,
                                        "kcmd": app.globalData.Course_Grade[i].name + '\n'
                                      }
                                      if (Index + 1 <= app.globalData.Course_Grade[i].lessons_time[j].week_to && Index + 1 >= app.globalData.Course_Grade[i].lessons_time[j].week_from && app.globalData.Course_Grade[i].year == app.globalData.term_now_year && app.globalData.Course_Grade[i].semester == app.globalData.term_now_semester) {
                                        lesson_result_Array.push(lesson_result);
                                      }
                                    }
                                  }
                                  if (num == 5) {
                                    num_jud = false
                                  }
                                  if (res.data == null && lesson_result_Array[0] == null && num_jud) {
                                    num = num + 1;
                                    _this.onLoad();
                                  }
                                  let weekday = new Date().getDay();
                                  if (weekday == 0) weekday = 7;
                                  if (charts_need_array[0] == null) {
                                    for (let i = 0; i < lesson_result_Array.length; i++) {
                                      if (lesson_result_Array[i].xqj == weekday) { //watch this
                                        if (lesson_result_Array[i].kcmd.length > 12) {
                                          lesson_result_Array[i].kcmd = lesson_result_Array[i].kcmd.slice(0, 12) + '...' + '\n';
                                        }
                                        charts_need_array.push(lesson_result_Array[i])
                                      }
                                    }
                                    for (let i = 0; i < charts_need_array.length; i++) {
                                      charts_need_array[i].skcd = charts_need_array[i].skcd + charts_need_array[i].skjc - 1;
                                    }
                                  }
                                  if (charts_need_array.length == 0) {
                                    var empty_result = {
                                      "xqj": '',
                                      "skjc": '',
                                      "skcd": '',
                                      "kcmc": '',
                                      "kcmd": '今日无事'
                                    }
                                    _this.setData({
                                      hid_jie: false
                                    })
                                    charts_need_array.push(empty_result);
                                  }
                                  _this.setData({
                                    Course_list: charts_need_array,
                                  })
                                  if (num == 5) {
                                    num_jud = false
                                  }
                                  if (charts_need_array[0] == null && num_jud) {
                                    num = num + 1;
                                    _this.onLoad();
                                  }
                                  ////////////////////////////////
                                },
                                Error: function(res) {
                                  wx.showToast({
                                    title: '登入失败',
                                    icon: 'cancel',
                                    duration: 2000,
                                  })
                                }
                              })

                            var c =
                              wx.request({
                                url: 'https://api.ziqiang.net.cn/settings/?name=term_begin_date,term_now_year,term_now_semester', //仅为示例，并非真实的接口地址
                                method: "GET",
                                data: {

                                },
                                dataType: JSON,
                                header: {
                                  'content-type': 'application/json', // 默认值
                                  'Authorization': 'Token ' + app.globalData.Token,
                                  'x-zswd-signature': sha1,
                                  'x-zswd-timestamp': timestamp,
                                  'x-zswd-nonce': ran,
                                },
                                success: function(res) {

                                  var data = JSON.parse(res.data);
                                  app.globalData.term_now_year = data.term_now_year;
                                  app.globalData.term_begin_date = data.term_begin_date;
                                  app.globalData.term_now_semester = data.term_now_semester - 1;
                                },
                                Error: function(res) {
                                  wx.showToast({
                                    title: '登入失败',
                                    icon: 'cancel',
                                    duration: 2000,
                                  })
                                }
                              })

                            /*var f =
                              wx.request({
                                url: 'https://api.ziqiang.net.cn/courses/grade', //仅为示例，并非真实的接口地址
                                method: "GET",
                                data: {
                                  "instructor":"李美幸",
                                },
                                dataType: JSON,
                                header: {
                                  'content-type': 'application/json', // 默认值
                                  'Authorization': 'Token ' + app.globalData.Token,
                                  'x-zswd-signature': sha1,
                                  'x-zswd-timestamp': timestamp,
                                  'x-zswd-nonce': ran,
                                },
                                success: function (res) {
      
                                  var data = JSON.parse(res.data);
                                 
      
                                },
                                Error: function (res) {
                                  wx.showToast({
                                    title: '登入失败',
                                    icon: 'cancel',
                                    duration: 2000,
                                  })
                                }
                              })*/

                          },
                          Error: function(res) {
                            wx.showToast({
                              title: '登入失败',
                              icon: 'cancel',
                              duration: 2000,
                            })
                          }
                        })
                    },

                  }) //三部获取图书馆密码
                },
              }) //二步获取

            },
            fail: function() {
              _this.setData({
                sid: '.尚未登入.',
              })
            },

          }) //一步获取账号
        }
      }) //四步获取wifi密码
      //各种数据的获取

      wx.hideTabBar({
        aniamtion: true
      });

      var _this = this;
      var _time = 3;
      var time_counter = setInterval(function() {
        _time = _time - 1;
        if (_time == 0) {

          let animation4 = wx.createAnimation({
            transformOrigin: "50% 50%",
            duration: 1500,
            timingFunction: "ease",
            delay: 0
          });
          animation4.opacity('0').step();
          _this.setData({
            mask_fade: animation4.export()
          });
          wx.showTabBar({
            aniamtion: true
          });
          var time_counter2 = setInterval(function() {

            clearInterval(time_counter2);
          }, 1500);
          _this.setData({
            mask_hide: true,
          })
          clearInterval(time_counter);
        }

      }, 1000); //各种开场蒙版的计时

      if (app.globalData.userInfo) {
        this.setData({
          userInfo: app.globalData.userInfo,
          hasUserInfo: true
        })
      } else if (this.data.canIUse) {
        // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
        // 所以此处加入 callback 以防止这种情况
        app.userInfoReadyCallback = res => {
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      } else {
        // 在没有 open-type=getUserInfo 版本的兼容处理
        wx.getUserInfo({
          success: res => {
            app.globalData.userInfo = res.userInfo
            this.setData({
              userInfo: res.userInfo,
              hasUserInfo: true
            })
          }
        })
      } //网络请求
    }
  },
  Countdown: function() {
    var that = this;
    timer = setTimeout(function() {
      that.onPullDownRefresh();
      if (that.data.wlist[0] == null) {
        that.Countdown();
      }
    }, 1000);
  },
  weekTap: function() {
    if (this.data.week_selector_open == 'on') {
      this.setData({
        week_selector_open: 'off',
        offset: 5.95
      })
    } else {
      this.setData({
        week_selector_open: 'on',
        offset: 0
      })
    }
    this.setData({
      scrollLeft: (this.data.weekNum - 1) * 46
    })
  },
  showCardView: function(e) {
    let cache = new Array(1);
    cache[0] = lesson_result_Array[e.currentTarget.dataset.index];
    this.setData({
      showData: cache
    })
  },
  close: function() {
    this.setData({
      showData: []
    })
  }

})